
const homedir = require('os').homedir();//获取电脑用户 home 目录
const home = process.env.HOME || homedir
const path = require('path')//内置路径处理工具
const db = require('./db.js')
const inquirer = require('inquirer')
function printAll(list) {
    inquirer.prompt([
        {
            type: "list",
            message: "请选择需要完成的任务：",
            name: "index",
            choices: [{ name: '退出', value: '-1' }, { name: '添加任务', value: '-2' },
            ...list.map((task, i) => {
                return { name: `${task.done ? '[x]' : '[_]'} ${i + 1}. ${task.title}`, value: i.toString() }
            }),]
        }
    ]).then(answer => {
        // 用户输入的结果最终会在这里输出
        if (answer.index >= 0) {//选中任务
            chooseTask(list, answer.index)
        } else if (answer.index == -2) {
            //创建任务
            createTask(list)
        }
    });
}
function chooseTask(list, index) {
    inquirer.prompt([
        {
            type: "list",
            message: "请选择操作：",
            name: "action",
            choices: [{ name: '退出', value: 'quit' },
            { name: '已完成', value: 'done' },
            { name: '未完成', value: 'undone' },
            { name: '改标题', value: 'rename' },
            { name: '删除', value: 'delete' }]
        }
    ]).then(answer => {
        switch (answer.action) {
            case 'done':
                list[index].done = true
                db.write(list)
                break
            case 'undone':
                list[index].done = false
                db.write(list)
                break
            case 'rename':
                renameTask(list, index)
                break
            case 'delete':
                list.splice(index, 1)
                db.write(list)
                break
        }
    })
}
function createTask(list) {
    inquirer.prompt([
        {
            type: "input",
            message: "输入任务标题：",
            name: "title",
        }
    ]).then(answer => {
        list.push({
            title: answer.title,
            done: false
        })
        db.write(list)
    })
}

function renameTask(list, index) {
    inquirer.prompt([
        {
            type: "input",
            message: "新标题名称：",
            name: "title",
            default: list[index].title
        }
    ]).then(answer => {
        list[index].title = answer.title
        db.write(list)
    })
}
module.exports.add = async (title) => {
    //面向接口编程
    //读取文件
    const list = await db.read()
    //添加新任务 title我拿到是数组 
    list.push({ title: title, done: false })
    //将新的任务列表写入文件
    await db.write(list)
}
module.exports.clear = async () => {
    list = []
    await db.write(list)
}
module.exports.showAll = async () => {
    //读取
    const list = await db.read()
    //打印任务
    printAll(list)
}